﻿using Apewer.Network;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace Apewer.Web
{

    /// <summary>API 服务程序。</summary>
    public abstract class ApiProvider : IDisposable
    {

        /// <summary>在调用 API 前，接收选项实例。</summary>
        public ApiOptions Options { get; set; }

        #region Implement

        /// <summary>调用 API 前的检查，可返回错误信息以忽略 POST 内容。</summary>
        public virtual string PreInvoke() { return null; }

        /// <summary>读取请求前的检查，可返回错误信息以忽略 POST 内容。</summary>
        public virtual string PreRead() { return null; }

        /// <summary>写入响应前的检查，可返回错误信息以终止输出。</summary>
        public virtual string PreWrite() { return null; }

        /// <summary>发送完毕后执行。</summary>
        public virtual void Sent() { }

        /// <summary>结束本次请求和响应。</summary>
        public virtual void End() { }

        /// <summary>释放非托管资源。</summary>
        public virtual void Dispose() { }

        #endregion

        #region Request

        /// <summary>获取 HTTP 方法。</summary>
        public abstract HttpMethod GetMethod();

        /// <summary>获取客户端的 IP 地址。</summary>
        public abstract string GetClientIP();

        /// <summary>获取请求的 URL。</summary>
        public abstract Uri GetUrl();

        /// <summary>获取请求的 Referrer。</summary>
        public abstract string GetReferrer();

        /// <summary>获取请求的头。</summary>
        public abstract HttpHeaders GetHeaders();

        /// <summary>获取请求的内容类型。</summary>
        public abstract string GetContentType();

        /// <summary>获取请求的内容长度。</summary>
        public abstract long GetContentLength();

        /// <summary>获取请求的内容。</summary>
        public abstract Stream RequestBody();

        #endregion

        #region Response

        /// <summary>设置 HTTP 状态。</summary>
        public abstract void SetStatus(int status, int subStatus = 0);

        /// <summary>设置响应的头。</summary>
        public abstract string SetHeader(string name, string value);

        /// <summary>设置响应的缓存秒数，设置为 0 即不允许缓存。</summary>
        public abstract void SetCache(int seconds);

        /// <summary>设置响应的缓存秒数。</summary>
        public abstract void SetContentType(string value);

        /// <summary>设置响应的内容长度。</summary>
        public abstract void SetContentLength(long value);

        /// <summary>设置响应重定向。</summary>
        public abstract void SetRedirect(string location);

        /// <summary>获取 Response 流。</summary>
        public abstract Stream ResponseBody();

        #endregion

    }

    /// <summary>API 服务程序。</summary>
    public abstract class ApiProvider<TContext> : ApiProvider
    {

        /// <summary>HttpContext</summary>
        public abstract TContext Context { get; }

    }

}
